<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * function:微信前端主页控制器
 * Date: 2017/8/15
 * Time: 13:24
 */
namespace app\index\controller;
use       think\Controller;
use       think\Request;
use       think\Db;
class Home extends Controller
{

public function _initialize()
{
    //设置SESSION的失效时间
    ini_set('session.gc_maxlifetime', 7200); //设置时间 
}
//主页
public function home()
{
    session_start();
    //vendor('jssdk.jssdk');
    //得到主页条件
    $fenlei=Request::instance()->get('type');
    $level =Request::instance()->get('level');
    //level 1=推荐 2=热门排行 3=最新发布 4 免费专区
    // if(!$fenlei)
    // {
    //     $fenlei="推荐";
    // }
    if(!$level)
    {
        $level="1";
    }
    $level_array=array('1'=>'http://mg.bonayiyou.com/index/home/home.html?type='.$fenlei.'&level=1',
        '2'=>'http://mg.bonayiyou.com/index/home/home.html?type='.$fenlei.'&level=2',
        '3'=>'http://mg.bonayiyou.com/index/home/home.html?type='.$fenlei.'&level=3',
        '4'=>'http://mg.bonayiyou.com/index/home/home.html?type='.$fenlei.'&level=4');
    $_SESSION['url']=Request::instance()->url(true);
	//得到所有分类
    $style=Db::table('x_room_stype')->where('name','neq','推荐')->select();
	  $dingyue_style=array();
    if(!isset($_SESSION['dingyu']))
    {
	  foreach ($style as $key => $value) {
		  $dingyu_style[]=$value['name'];
	  }	
      $_SESSION['dingyu']=$dingyu_style;  
    }
    //如果是ajax 下拉加载
    if(Request::instance()->isAjax())
    {
      $add=Db::table('x_room')->where('room_stype',$fenlei)->order('popul_num desc')->limit($_SESSION['fenye'],5)->select();
      $_SESSION['fenye']+=5;
      foreach ($add as $key => $value) {
      $value['beg_time']=begintime($value['beg_time']);
      }
      if($add)
      {
      echo json_encode($add);
      }
      else{
      echo "[]";  
      }
    }   
    else {
    if(isset($_SESSION['openid'])){
    //$user_id=$_SESSION['user_id'];
    //$Jssdk=new \JSSDK();
    //$SignPackage=$Jssdk->GetSignPackage();
    //$this->assign('SignPackage',$SignPackage); 
    $h_d_receive=array();
    //得到用户订阅的栏位
    $dingyu=$_SESSION['dingyu'];
    //计算订阅
    foreach ($style as $key => $value) {
        //如果在订阅中找的到的话
        for($i=0;$i<count($dingyu);$i++)
        {
            
            if($dingyu[$i]==$value['name'])
            {    
            $h_d_receive[]=array($value['name'],"http://mg.bonayiyou.com/index/home/home.html?type=".$value['name'],1);
            break;
            }  
        }
        //不是订阅的栏位
        if($i==count($dingyu))
        {
            $h_d_receive[]=array($value['name'],"http://mg.bonayiyou.com/index/home/home.html?type=".$value['name'],0);
        }
    }
    //根据类别分别查询
    //如果有分类就不是首页
    if($fenlei)
    {
    switch ($level) {
         case '1':         
             $course=Db::table('x_room')->where('room_stype',$fenlei)->where('is_good',1)->order('room_id desc')->limit(0,5)->select();
             break;
         case '2':
             $course=Db::table('x_room')->where('room_stype',$fenlei)->order('popul_num desc')->limit(0,5)->select();            
             break;
         case '3':
             $course=Db::table('x_room')->where('room_stype',$fenlei)->order('create_time desc')->limit(0,5)->select();
             break;
         case '4':
             $course=Db::table('x_room')->where('room_stype',$fenlei)->where('room_price','免费')->order('create_time desc')->limit(0,5)->select();
             break;
         default:
             break;
     }
    $this->assign("dingyue_class",$fenlei); 
    }
    else
    {
   switch ($level) {
         case '1':         
             $course=Db::table('x_room')->where('is_good',1)->order('popul_num desc')->limit(0,5)->select();
             break;
         case '2':
             $course=Db::table('x_room')->order('popul_num desc')->limit(0,5)->select();            
             break;
         case '3':
             $course=Db::table('x_room')->order('create_time desc')->limit(0,5)->select();
             break;
         case '4':
             $course=Db::table('x_room')->where('room_price','免费')->order('popul_num desc')->limit(0,5)->select();
             break;
         default:
             break;
     }
    $this->assign("dingyue_class","推荐");
    }
    //轮播图
     if(!$fenlei)
     {
     $type_lunbo=Db::table('x_room_stype')->where('name','推荐')->find();
     }
     else
     {
     $type_lunbo=Db::table('x_room_stype')->where('name',$fenlei)->find();
     }
     $lunbo_picture=Db::table('x_roomstype_pic')->where('type_id',$type_lunbo['id'])->select();
     $_SESSION['fenye']=5;
     //计算课程的状态
     for($i=0;$i<count($course);$i++)
     {
      if($course[$i]['beg_time']==0)
      {
      $course[$i]['zhuangtai']=begintime($course[$i]['create_time']);
      }
      else if($course[$i]['beg_time']!=0&&$course[$i]['longtime']==0)
      {
      $course[$i]['zhuangtai']="<a style='text-decoration:none;color:green;'>正在直播|||</a>";  
      }
      else
      {
      $course[$i]['zhuangtai']="时长:".$course[$i]['longtime']."分钟"; 
      }
     }
     $this->assign('lunbo',$lunbo_picture);
     $this->assign('level',$level_array);
     $this->assign('room',$course);
     $this->assign('loadmore',"http://mg.bonayiyou.com/index/home/load_more?fenlei=".$fenlei."&level=".$level);
     $this->assign('dingyu',json_encode($h_d_receive));
     return $this->fetch();
    }
    }
    //在网页授权中获取用户信息
     $this->byauth();



}
public function load_more()
{
      session_start();
      $fenlei=Request::instance()->get('type');
      $level=Request::instance()->get('level');
      if($fenlei)
      {
      switch ($level) {
         case '1':         
             $add=Db::table('x_room')->where('room_stype',$fenlei)->where('is_good',1)->order('popul_num desc')->limit($_SESSION['fenye'],5)->select();
             break;
         case '2':
             $add=Db::table('x_room')->where('room_stype',$fenlei)->order('popul_num desc')->limit($_SESSION['fenye'],5)->select();            
             break;
         case '3':
             $add=Db::table('x_room')->where('room_stype',$fenlei)->order('create_time desc')->limit($_SESSION['fenye'],5)->select();
             break;
         case '4':
             $add=Db::table('x_room')->where('room_stype',$fenlei)->where('room_price','免费')->order('create_time desc')->limit($_SESSION['fenye'],5)->select();
             break;
         default:
             break;
     }
    }
    else
    {
   switch ($level) {
         case '1':         
             $add=Db::table('x_room')->where('is_good',1)->order('popul_num desc')->limit($_SESSION['fenye'],5)->select();
             break;
         case '2':
             $add=Db::table('x_room')->where('is_good',1)->order('popul_num desc')->limit($_SESSION['fenye'],5)->select();            
             break;
         case '3':
             $add=Db::table('x_room')->where('is_good',1)->order('create_time desc')->limit($_SESSION['fenye'],5)->select();
             break;
         case '4':
             $add=Db::table('x_room')->where('is_good',1)->where('room_price','免费')->order('create_time desc')->limit($_SESSION['fenye'],5)->select();
             break;
         default:
             break;
     }
    }
      $_SESSION['fenye']+=5;
      for($i=0;$i<count($add);$i++)
      {
      if($add[$i]['beg_time']==0)
      {
      $add[$i]['zhuangtai']=begintime($add[$i]['create_time']);
      }
      else if($add[$i]['beg_time']!=0&&$add[$i]['longtime']==0)
      {
      $add[$i]['zhuangtai']="<a style='text-decoration:none;color:green;'>正在直播|||</a>";  
      }
      else
      {
      $add[$i]['zhuangtai']="时长:".$add[$i]['longtime']."分钟"; 
      }
     }
      if($add)
      {
		//给人气加倍数
        for($i=0;$i<count($add);$i++)
		{
			$add[$i]['popul_num']=add_wan($add[$i]['popul_num']);
		}			
      echo json_encode($add);
      }
      else{
      echo "[]";  
      }
}
public function load_more_mohu()
{
      session_start();
      $key=Request::instance()->get('key');
      $room=Db::table('x_room')->where('title','like','%'.$key.'%')->order('popul_num  desc')->limit($_SESSION['fenye_search'],10)->select();
      $_SESSION['fenye_search']+=10;
      for($i=0;$i<count($room);$i++)
      {
      if($room[$i]['beg_time']==0)
      {
      $room[$i]['zhuangtai']=begintime($room[$i]['create_time']);
      }
      else if($room[$i]['beg_time']!=0&&$room[$i]['longtime']==0)
      {
      $room[$i]['zhuangtai']="<a style='text-decoration:none;color:green;'>正在直播|||</a>";  
      }
      else
      {
      $room[$i]['zhuangtai']="时长:".$room[$i]['longtime']."分钟"; 
      }
     }
      if($room)
      {
        echo json_encode($room);
      }
      else{
        echo "[]";
      }

}
//搜索页面
public function index_research()
{
  session_start();
  //得到关键词
  $key =Request::instance()->get('key');
  $room=Db::table('x_room')->where('title','like','%'.$key.'%')->order('popul_num  desc')->limit(0,10)->select();
  $_SESSION['fenye_search']=5;
   for($i=0;$i<count($room);$i++)
     {
      if($room[$i]['beg_time']==0)
      {
      $room[$i]['zhuangtai']=begintime($room[$i]['create_time']);
      }
      else if($room[$i]['beg_time']!=0&&$room[$i]['longtime']==0)
      {
      $room[$i]['zhuangtai']="<a style='text-decoration:none;color:green;'>正在直播|||</a>";  
      }
      else
      {
      $room[$i]['zhuangtai']="时长:".$room[$i]['longtime']."分钟"; 
      }
     }
  $this->assign('room',$room);
  $this->assign('loadmore_mohu',"http://mg.bonayiyou.com/index/home/load_more_mohu?key=".$key);
  return $this->fetch();  

}

/*网页授权获取用户信息静默方式不会弹出需要用户授权的页面*/
public function byauth(){
    //公众号在微信的appid
    $appid = "wxcd4dce13c9fb1a0a";
    //重定向到回调地址
    $redirect_uri =urlencode('http://mg.bonayiyou.com/index/home/getUserInfo');
    /*应用授权作用域，snsapi_base （不弹出授权页面，直接跳转，只能获取用户openid）
    snsapi_userinfo （弹出授权页面，可通过openid拿到昵称、性别、所在地。
    并且，即使在未关注的情况下，只要用户授权，也能获取其信息）*/
    $scope = 'snsapi_base';
    //重定向后会带上state参数，开发者可以填写a-zA-Z0-9的参数值，最多128字节
    $state = '';
    //进行重定向操作
    $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$appid.'&redirect_uri='.$redirect_uri.'&response_type=code&scope='.$scope.'&state='.$state.'#wechat_redirect';
    header("Location:".$url);
}
//得到用户信息
function getUserInfo(){
    session_start();
    //通过code换取网页授权access_token（访问令牌）
    $appid = "wxcd4dce13c9fb1a0a";//公众号在微信的appid
    $secret = "a9f3c9753b70b42573fdd6440090c1c6";//微信生成的秘钥
    $code = $_GET["code"];
    $get_token_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$appid.'&secret='.$secret.'&code='.$code.'&grant_type=authorization_code';
    $json_obj =json_decode($this->http_curl($get_token_url));
    //获取用户的openid  我这里就返回的openid 用于判断用户是不是存在
    $openid=$json_obj->openid;
    $_SESSION['openid']=$openid;
    $openid=$_SESSION["openid"];
    //通过opendid找到用户的user_id存入SESSION中方便以后使用
    
    $data  =Db::table('x_weixin_user')->where('openid',$openid)->find();
    if(!$data)
    {
      $_SESSION['user_id']=$this->is_user_id_null($openid);
    }
    else
    {
      $_SESSION['user_id']=$data['id']; 
    }
    $this->redirect($_SESSION['url']);
    //echo $json_obj->openid;
    //refresh_token有效期为30天，当refresh_token失效之后，需要用户重新授权。
    //$refresh_token=$json_obj['refresh_token'];
    //获取第二步的refresh_token后，请求以下链接获取access_token：
    //$get_user_info_url="https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=".$appid."&grant_type=refresh_token&refresh_token=".$refresh_token;
    //获取到用户信息
    //$userinfo = $this->http_curl($get_user_info_url);
}
//curl
public function  http_curl($url,$data=null){
    //1.初始化，创建一个新cURL资源
    $ch = curl_init();
    //2.设置URL和相应的选项
    curl_setopt($ch, CURLOPT_URL, $url);
    //curl_setopt($ch, CURLOPT_HEADER, 0);
    if(!empty($data)){
    curl_setopt($ch,CURLOPT_POST,1);
    curl_setopt($ch,CURLOPT_POSTFIELDS,$data);
    }
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);//不检测服务器的证书是否由正规浏览器认证过的授权CA颁发
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);//不检测服务器的域名与证书上的是否一致
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);//禁止curl资源直接输出
    //3.抓取URL并把它传递给浏览器
    $opt=curl_exec($ch);
    //4.关闭cURL资源，并且释放系统资源
    curl_close($ch);
    return $opt;
}
//用户上传图片
public function post_img()
{
    $base64_image_content = $_POST['base64img'];
    $output_directory = 'uploads/'.date('Y-m-d'); //设置图片存放路径

    /* 检查并创建图片存放目录 */
    if (!file_exists($output_directory)) {
    mkdir($output_directory, 0777);
    }

    /* 根据base64编码获取图片类型 */
    if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)) {
    $image_type = $result[2]; //data:image/jpeg;base64,
    $output_file = $output_directory . '/' . md5(time()) . '.' . $image_type;
    }

    /* 将base64编码转换为图片编码写入文件 */
    $image_binary = base64_decode(str_replace($result[1], '', $base64_image_content));
    if (file_put_contents($output_file, $image_binary)) {
    echo '/'.$output_file; //写入成功输出图片路径
}
}
//直播间
public function weike_chizbo()
{
    //引入jssdk类用于调用录音接口
    vendor('jssdk.jssdk');
    session_start();
    $user_id=$_SESSION['user_id'];
    $Jssdk=new \JSSDK();
    $SignPackage=$Jssdk->GetSignPackage();
    //获取房间ID
    $RoomId=Request::instance()->get('room_id');
    //获取房间信息
    $RoomMessage=Db::table('x_room')->where('room_id',$RoomId)->find();
    //获取用户的ID
    $List  =Db::table('x_weixin_user')->where('openid',$_SESSION["openid"])->find();
    $UserId=$List['id'];
    //添加听课记录
    if(!Db::table('x_lis_recoder')->where('user_id',$UserId)->where('room_id',$RoomId)->find()&&$user_id!=$RoomMessage['user_id'])
    {
        Db::table('x_lis_recoder')->insert(array('user_id'=>$UserId,'room_id'=>$RoomId));
        Db::table('x_user')->where('user_id',$RoomMessage['user_id'])->setInc('pol_num');
        //房间人气值加1
        Db::table('x_room')->where('room_id',$RoomId)->setInc('popul_num');
    }
    //查询该用户购买了这个房间没有如果没有购买定位到购买页面
    $is_buy=Db::table('x_pay_recoder')->where('user_id',$UserId)->where('room_id',$RoomId)->find();
    //查看这个房间有多少人进来过
    $CountNumber=Db::table('x_lis_recoder')->where('room_id',$RoomId)->count();
    $NickName=$List['nickname'];
    $HeadPic=$List['headimgurl'];
    //根据房间ID获取老师ID
    $List  =Db::table('x_room')->where('room_id',$RoomId)->find();
    if(!$is_buy&&trim($List['room_price'])!="免费"&&$UserId!=$user_id)
    {
        $this->redirect("http://mg.bonayiyou.com/index/home/class_pay?room_id=".$RoomId);
    }
    $RoomUserId=$List['user_id'];

    //获取主播的信息
    $ListTeacher=Db::table('x_user')->where('user_id',$RoomUserId)->find();

    //如何用户就是老师的话
    if($UserId==$RoomMessage['user_id'])
    {
      $HeadPic=$ListTeacher['headpic'];
    }
    //根据房间ID获取音频
    $ListVoice=Db::query('select *from x_voice_list where x_voice_list.room_id='.$RoomId);
    //判断有限期有没有过2天
    if($ListVoice)
    {
     if(time()-$ListVoice[0]['create_time']<215000)
     {
        //代表还可以用微信服务资源
         $this->assign('method','amr');
     }
    //使用服务器资源
    else
    {
        //替换音频文件的src
        for ($i=0;$i<count($ListVoice);$i++) {
            $ListVoice[$i]['tem_voice']="http://mg.bonayiyou.com/uploads/voice/".date("Y-m-d",$ListVoice[$i]['create_time'])."/".$ListVoice[$i]['tem_voice'].".mp3";
        }
        $this->assign('method','mp3');
    
    }
    }
    //查询最新的15条评论
    $ListText =Db::query("select * from x_text_list, x_weixin_user where x_text_list.user_id=x_weixin_user.id and x_text_list.room_id=$RoomId order by create_time desc limit 25");
    //得到评论的总条数
    $count_pinglun=Db::table('x_text_list')->where('room_id',$RoomId)->count();
    if(!$ListText)
    {
        $count=0;
    }
    else
    {
        $count=count($ListText);
    }
    //弹幕数组
    $ListDanmu=array();    
    //判断取到的评论的条数
    if($count<4)
    {
        foreach ($ListText as $key => $value) {
            $ListDanmu[]=$value;
        }
        for($i=0;$i<4-count($ListText);$i++)
        {
            $ListDanmu[]=array(
                'headimgurl'=>"http://mg.bonayiyou.com/static/weike/img/u=2767795787,2943094574&fm=27&gp=0.jpg",
                'content'   =>"暂时还没有评论哦!"
                );
        }
    }
    else
    {
       for($i=0;$i<4;$i++)
        {
            $ListDanmu[]=array(
                'headimgurl'=>$ListText[$i]['headimgurl'],
                'content'   =>$ListText[$i]['content']
                );
        } 
    }

    //查看进入者是不是关注了这个老师
    $is_follow=Db::table('x_attn_recoder')->where('user_id',$UserId)->where('teacher_id',$RoomUserId)->find();
    if($is_follow)
    {
        $this->assign('follow',"checked");
    }
    else
    {
        $this->assign('follow',"");
    }
    //判断进入者的身份是老师还是学生
    if($RoomUserId==$UserId)
    {
        $this->assign('identify',"teacher");
    }
    else
    {
        $this->assign('identify',"student");
    }
    //得到房间轮播图
    $room_lunbo=Db::table('x_room_lunbo')->where('room_id',$RoomId)->select();
    $room_lunbo_count=Db::table('x_room_lunbo')->where('room_id',$RoomId)->count();
    //找到历史语音中最大的sort
    $MaxSort=Db::table('x_voice_list')->where('room_id',$RoomId)->max('sort');
    if(!$MaxSort)
    {
      $MaxSort=1;
    }
    else
    {
      $MaxSort+=1;
    }
    //判断房间是不是结束了
    if($RoomMessage['longtime']!=0)
    {
    $this->assign("is_run",2);  
    }
    else if($RoomMessage['beg_time']!=0)
    {
    $this->assign("is_run",1);    
    }
    else{
    $this->assign("is_run",0);  
    }
    $this->assign('count_pinglun',$count_pinglun);
    $this->assign('room_lunbo_count',$room_lunbo_count);  
    $this->assign("MaxSort",$MaxSort);
    $this->assign("RoomLunbo",$room_lunbo);
    $this->assign('CountNumber',$CountNumber);
    $this->assign('Title',$RoomMessage['title']);
    $this->assign('ListDanmu',$ListDanmu);
    $this->assign('ListVoice',$ListVoice);
    $this->assign('ListText',$ListText);
    $this->assign('SignPackage',$SignPackage);
    $this->assign('RoomId',$RoomId);
    $this->assign('UserId',$UserId);
    $this->assign('RoomUserId',$RoomUserId);
    $this->assign('NickName',$NickName);
    $this->assign('HeadPic',$HeadPic);
    $this->assign('ListTeacher',$ListTeacher);
    return $this->fetch();

}   

//付款
//支付页面传过来的参数应该是商品的信息
public function class_pay()
{
    session_start();
    vendor('Wxpay.Wxpay');//加载支付文件 支付文件中包括了 统一支付接口类 jsapi 类 日志文件类
    if(isset($_SESSION['user_id']))
    {
    //获取房间参数得到房间参数
    $room_id=intval(Request::instance()->get('room_id'));
    //获取用户id
    $user_id=$_SESSION['user_id'];
    $room=Db::table('x_room')->where('room_id',$room_id)->find();
    //讲师介绍
    $teacher=Db::table('x_user')->where('user_id',$room['user_id'])->find();
    if(trim($room['room_price'])=="免费")
    {
        $room['room_price']=0;
    }
    else
    {
        $room['room_price']=number_format((float)$room['room_price'],2);
      
    }
    //将房间的信息存SESSION用于购买回调时填充数据库
    $_SESSION['room_price']=$room['room_price'];
    $_SESSION['room_id']=$room['room_id'];
    //配置 用户是不是购买 是不是收藏 是不是关注
    //默认都为0
    $config=array(
        'is_buy'=>0,
        'is_follow'=>0,
        'is_collector'=>0,
        );
    //查看该用户购买这个课程没有
    $is_buy=Db::table('x_pay_recoder')->where('user_id',$user_id)->where('room_id',$room_id)->find();
    //如果是老师有编辑课程的能力
    if($user_id==$room['user_id'])
    {
      $this->assign('identity',"teacher");
    }
    else
    {
      $this->assign('identity',"student");
    }
    if($is_buy||$room['room_price']==0||$user_id==$room['user_id'])
    {
    $config['is_buy']=1;
    }
    //查看是不是关注了的
    $is_follow=Db::table('x_attn_recoder')->where('teacher_id',$room['user_id'])->where('user_id',$user_id)->find();
    if($is_follow)
    {
    $config['is_follow']=1;    
    }
    //查看是不是收藏了
    $is_collector=Db::table('x_collect_recoder')->where('room_id',$room_id)->where('user_id',$user_id)->find();
    if($is_collector)
    {
    $config['is_collector']=1;      
    }
    //如果用户没有购买的话
    if($config['is_buy']==0)
    {
    //①、获取用户openid
    $tools = new \JsApiPay();
    if(!isset($_SESSION['openid']))
    {
    $openId = $tools->GetOpenid($room_id);
    }
    else
    {
    $openId=$_SESSION['openid'];     
    }
    //②、统一下单
    $input = new \WxPayUnifiedOrder();
    $input->SetBody($room['title']);//商品详情
    $input->SetAttach($room['room_id']);//附加信息，可用作后台验证添加信息
    $input->SetOut_trade_no(\WxPayConfig::MCHID.date("YmdHis"));//订单号
    $input->SetTotal_fee($room['room_price']*100);//支付金额，必须乘以100，不然1就是0.01
    $input->SetTime_start(date("YmdHis"));//开始时间
    $input->SetTime_expire(date("YmdHis", time() + 600));//终止时间
    $input->SetGoods_tag("我是标签");
    $input->SetNotify_url("http://mg.bonayiyou.com/index/home/notify");//回调地址
    $input->SetTrade_type("JSAPI");
    $input->SetOpenid($openId);
    //获取order信息
    $order = \WxPayApi::unifiedOrder($input);
    $jsApiParameters = $tools->GetJsApiParameters($order);
    $this->assign('jsApiParameters',$jsApiParameters);
    }
    if(!isset($jsApiParameters))
    {
    $this->assign('jsApiParameters',"123");
    }
    if($room['beg_time']==0)
    {
      $room['zhuangtai']=begintime($room['create_time']);
    }
    else if($room['beg_time']!=0&&$room['longtime']==0)
    {
    $room['zhuangtai']="<a style='text-decoration:none;color:green;'>正在直播|||</a>";  
    }
    else
    {
      $room['zhuangtai']="时长:".$room['longtime']."分钟"; 
    }
    $this->assign('user_id',$user_id);
    $this->assign('teacher',$teacher);
    $this->assign('config',"[".json_encode($config)."]");
    $this->assign('room',$room);
    $this->assign('room_id',$room['room_id']);
    return $this->fetch();
  }
    $_SESSION['url']=Request::instance()->url(true);
    $this->byauth(); 
}

//支付回调
public function notify(){
   // session_start();
    $xml= file_get_contents("php://input");
    file_put_contents('log.txt',simplexml_load_string($xml));
    // $data=array(
    //      'user_id'=>$_SESSION['user_id'],
    //      'room_price'=>$_SESSION['room_price'],
    //      'room_id'=>$_SESSION['room_id'],
    //     'create_time'=>time() 
    //     );
    //   file_put_contents('log.txt',json_encode($data));
    //   Db::table('x_pay_recoder')->insert($data);
    
}

//微课中心页面渲染
public function weike_center()
{
    //判断是不是其他人进入微课中心
    session_start();
    if(isset($_SESSION['user_id']))
    {
    $user_id=$_SESSION["user_id"];
    $data=Db::table('x_user')->where('user_id',$user_id)->find();
    if($data)
    {
          $this->assign("person",$data);
    }
    else
    {
        $weixin_data=Db::table('x_weixin_user')->where('id',$user_id)->find();
        $weixin_data['cen_num']=0;
        $weixin_data['pol_num']=0;
        $weixin_data['headpic']=$weixin_data['headimgurl'];
        $weixin_data['profit'] =number_format(0,2);
        $this->assign('person',$weixin_data);
    }
    return $this->fetch();
   }   
    $_SESSION['url']=Request::instance()->url(true);
    $this->byauth();  
}

//个人中心页面渲染
public function person_center()
{
    session_start();
    if(isset($_SESSION['user_id']))
    {
    $user_id=$_SESSION["user_id"];
    $user=Db::table('x_user')->where('user_id',$user_id)->find();
    if($user)
    {
        $this->assign('person',$user);
        return $this->fetch();
    }
    else
    {
        $person=Db::table('x_weixin_user')->where('id',$user_id)->find();
        $person['introduce']="请先在微课中心创建我的直播间,编写个人介绍";
        $person['headpic']=$person['headimgurl'];
        $person['cen_num']=0;
        $person['pol_num']=0;
        $this->assign('person',$person);
        return $this->fetch();
    }
    $_SESSION['url']=Request::instance()->url(true);
    $this->byauth();  
   }
}

//创建直播间渲染页面
public function person_zhibocreate()
{
    session_start();
    if(Request::instance()->isAjax())
    {
    $data=Request::instance()->post();
    $data['create_time']=time();
    $offest=Db::table('x_user')->insert($data);
     if($offest){
        return json(["code"=>1]);
    }
     return json(['code'=>-1]);
    }
    else
    {
    $user_id=$_SESSION['user_id'];
    $data=Db::table('x_weixin_user')->where('id',$user_id)->find();
    $content=file_get_contents('yingshi.txt');
    $this->assign('content',$content);
    $this->assign('message',$data);
    return $this->fetch();
    }
}
//创建课程
public function person_createobj()
{  
   session_start();
   $user_id=$_SESSION['user_id'];
   //判断该老师是不是创建了直播间如果没有直接跳到创建直播间页面
   if(!Db::name('x_user')->where('user_id',$user_id)->find())
   {
      $this->redirect('http://mg.bonayiyou.com/index/home/person_zhibocreate.html');
   }
   if(Request::instance()->isAjax())
   {
    $data=Request::instance()->post();
    $data['create_time']=strtotime($data['beg_time']);
    $data['beg_time']=0;
    $data['user_id']=$_SESSION['user_id'];
    $person=Db::table('x_user')->where('user_id',$user_id)->find();
    $data['teachername']=$person['nickname'];
    $offest=Db::table('x_room')->insertGetId($data);
    if($offest){
    //生成直播间二维码
    $url="http://mg.bonayiyou.com/index/home/class_pay?room_id=".$offest;
    getqrcode($url,$offest);
    return json(["code"=>1,"id"=>$offest]);
    }
    return json(['code'=>-1]);
   }
   else
   {
   //得到所有课程的分类
   $room_stype=Db::table('x_room_stype')->where('name','neq','推荐')->select(); 
   $content=file_get_contents('yingshi.txt');
   $this->assign('content',$content);
   $this->assign("room_stype",$room_stype);

   return $this->fetch();
   } 
}
//直播间页面
public function person_zhibo()
{
     session_start();
     if(Request::instance()->get('user_id'))
     {
     $user_id=Request::instance()->get('user_id');
     $this->assign('identify',"student");   
     }
    else
     {
    $user_id=$_SESSION['user_id']; 
    $this->assign('identify',"teacher");  
     }
   $data=Db::table('x_user')->where('user_id',$user_id)->find();
   if($data)
   {
   //得到直播间所有的课程
   $room=Db::table('x_room')->where('user_id',$user_id)->select();
  for($i=0;$i<count($room);$i++)
     {
      if($room[$i]['beg_time']==0)
      {
      $room[$i]['zhuangtai']=begintime($room[$i]['create_time']);
      }
      else if($room[$i]['beg_time']!=0&&$room[$i]['longtime']==0)
      {
      $room[$i]['zhuangtai']="<a style='text-decoration:none;color:green;'>正在直播|||</a>";  
      }
      else
      {
      $room[$i]['zhuangtai']="时长:".$room[$i]['longtime']."分钟"; 
      }
     }
   $lunbo=Db::table('x_person_lunbo')->where('user_id',$user_id)->order('id desc')->select();
   if(count($lunbo)>4)
   {
       for($i=0;$i<4;$i++)
       {
       $newdata[$i]=$lunbo[$i];   
       }
   $this->assign('lunbo',$newdata);   
   }
   else if(!$lunbo)
   {
    $newdata[0]=array('img_cover'=>'/static/weike/img/zhibolunbo_re.gif','src'=>'');
    $this->assign('lunbo',$newdata);  
   }
   else{
   $this->assign('lunbo',$lunbo); 
   }
   $this->assign('person',$data);
   $this->assign('room',$room);
   return $this->fetch(); 
   }
   //如果不存在创建直播间
   $this->redirect('http://mg.bonayiyou.com/index/home/person_zhibocreate.html');
}
//课程管理页面
public function person_manageobj()
{
    session_start();
    $user_id=$_SESSION['user_id'];
    $room=Db::table('x_room')->where('user_id',$user_id)->select();
     for($i=0;$i<count($room);$i++)
     {
      if($room[$i]['beg_time']==0)
      {
      $room[$i]['zhuangtai']=begintime($room[$i]['create_time']);
      }
      else if($room[$i]['beg_time']!=0&&$room[$i]['longtime']==0)
      {
      $room[$i]['zhuangtai']="<a style='text-decoration:none;color:green;'>正在直播|||</a>";  
      }
      else
      {
      $room[$i]['zhuangtai']="时长:".$room[$i]['longtime']."分钟"; 
      }
     }
    $this->assign('room',$room);
    return $this->fetch();
}
//删除课程
public function del_room()
{
    $room_id=Request::instance()->post('room_id');
    $offest=DB::table('x_room')->where('room_id',$room_id)->delete();
    if($offest){
    return json(["code"=>1]);
    }
    return json(['code'=>-1]);
}
//编辑课程
public function person_updateobj()
{
    $room_id=Request::instance()->get('room_id');
    if(Request::instance()->isAjax())
    {
   
     $data   =Request::instance()->post();
     $data['create_time']=strtotime($data['beg_time']);
	 unset($data['beg_time']);
     $offest =Db::table('x_room')->where('room_id',$room_id)->update($data);
     if($offest){
     return json(["code"=>1]);
     }
     return json(['code'=>-1]);

    }
    else
    {
        $room=Db::table('x_room')->where('room_id',$room_id)->find();
         //得到所有课程的分类
        $room_stype=Db::table('x_room_stype')->where('name','neq','推荐')->select();
        $content=file_get_contents('yingshi.txt');
        $this->assign('content',$content); 
        $this->assign("room_stype",$room_stype);
        $this->assign('room',$room);
        return $this->fetch();
    }
  
}
//轮播图添加
public function weike_img_change()
{
    session_start();
    $user_id=$_SESSION['user_id'];
    if(Request::instance()->isAjax())
    {
        //如果存在轮播图先把以前的删除了
        Db::table('x_person_lunbo')->where('user_id',$user_id)->delete();
        $data=json_decode(htmlspecialchars_decode(Request::instance()->post('data')),true);
        $senddata=array();
        foreach ($data as $key => $val){
          if($val[0]=="")
            break;
          DB::table('x_person_lunbo')->insert(array('user_id'=>$user_id,'img_cover'=>$val[0],'src'=>$val[1]));
        }
        return json(["code"=>1]);
    }
    else{
    //如果存在轮播图先渲染出来
    $count=Db::table('x_person_lunbo')->where('user_id',$user_id)->count();
    $lunbo=Db::table('x_person_lunbo')->where('user_id',$user_id)->order('id desc')->select();
    if($count<4)
    {
    for($i=$count;$i<4;$i++)
    {
        $lunbo[$i]['img_cover']="";
        $lunbo[$i]['src']="";
        $lunbo[$i]['id']="";
    }
    $lunbo_length=$count;
    }
    else
    {
        $lunbo_length=4;
    }   
    $room=Db::table('x_room')->where('user_id',$user_id)->select();
    $this->assign('lunbo_length',$lunbo_length);
    $this->assign('lunbo',$lunbo);
    $this->assign('room',$room); 
    return $this->fetch();
    }
}

//编辑个人资料
public function person_edit()
{
    session_start();
    $user_id=$_SESSION['user_id'];
    if(Request::instance()->isAjax())
    {
    $data=Request::instance()->post();
    $data['create_time']=time();
    $offest=Db::table('x_user')->where('user_id',$user_id)->update($data);
    if($offest){
        return json(["code"=>1]);
    }
     return json(['code'=>-1]);
    }
    else{
    $person=Db::table('x_user')->where('user_id',$user_id)->find();
    $content=file_get_contents('yingshi.txt');
    $this->assign('content',$content);
    $this->assign('person',$person);
    return $this->fetch();
    }
}

//提现页面
public function weike_reflect()
{
    session_start();
    $user_id=$_SESSION['user_id'];
    if(Request::instance()->isAjax())
    {
    $data=Request::instance()->post();
    $person=Db::table('x_weixin_user')->where('id',$user_id)->find();
    $data['create_time']=time();
    $data['user_id']    =$user_id;
    $data['nickname']   =$person['nickname'];
    $data['money']=$data['money']*100;
    //减掉收益
    Db::table('x_user')->where('user_id',$user_id)->setDec('profit',$data['money']);
    $offest=Db::table('x_getmoney_list')->insert($data);
    if($offest){
     return json(["code"=>1]);
    }
     return json(['code'=>-1]);   
    }
    else{
        $person=Db::table('x_user')->where('user_id',$user_id)->find();
        $this->assign('person',$person);
        return $this->fetch();
    }
}
//待审核页面
public function register_chosuc()
{
    $this->assign('time',time());
    return $this->fetch();
}
//添加关注
public function add_follow()
{
session_start();
$user_id=$_SESSION['user_id'];  
$data=Request::instance()->post();
//查看是不是自己
if($user_id!=$data['teacher_id'])
{
Db::table('x_attn_recoder')->insert($data);
//粉丝自增1
Db::table('x_user')->where('user_id',$data['teacher_id'])->setInc('cen_num');
}
}
//添加收藏
public function add_collect()
{
$data=Request::instance()->post();
Db::table('x_collect_recoder')->insert($data);
}
//删除关注
public function del_follow()
{
$data=Request::instance()->post();
Db::table('x_attn_recoder')->where(['user_id'=>$data['user_id'],'teacher_id'=>$data['teacher_id']])->delete();
}
//删除收藏
public function del_collect()
{
$data=Request::instance()->post();
Db::table('x_collect_recoder')->where(['user_id'=>$data['user_id'],'room_id'=>$data['room_id']])->delete();
}
//添加订单数据
public function add_pay_recoder()
{
    $data=Request::instance()->post();
    $data['create_time']=time();
    $data['room_price']=$data['room_price']*100;
    Db::table('x_pay_recoder')->insert($data);
    //教师添加收益
    $person=Db::table('x_room')->where('room_id',$data['room_id'])->find();
    Db::table('x_user')->where('user_id',$person['user_id'])->setInc('profit',$data['room_price']);
}

//所有常见页面的集合包括 听课记录 购买记录 收藏记录 
public function active_recoder()
{
    //type=1听课记录
    //type=2收藏记录
    //type=3购买记录
    session_start();
    $user_id=$_SESSION['user_id'];
    $type=Request::instance()->get('type');
    if($type=='1')
    {
            $room=array();
            $data=Db::table('x_lis_recoder')->where('user_id',$user_id)->select();
            foreach ($data as $key => $value) {
            if(Db::table('x_room')->where('room_id',$value['room_id'])->find())  
            $room[]=Db::table('x_room')->where('room_id',$value['room_id'])->find();    
            }  
            $this->assign('title',"听课记录");
    }
    else if($type=='2')
    {
            $room=array();
            $data=Db::table('x_collect_recoder')->where('user_id',$user_id)->select();
            foreach ($data as $key => $value) {
            if(Db::table('x_room')->where('room_id',$value['room_id'])->find())  
            $room[]=Db::table('x_room')->where('room_id',$value['room_id'])->find();  
        }
        $this->assign('title',"收藏记录");
    }
    else{
            $room=array();
            $data=Db::table('x_pay_recoder')->where('user_id',$user_id)->select();
            foreach ($data as $key => $value) {
            if(Db::table('x_room')->where('room_id',$value['room_id'])->find())  
            $room[]=Db::table('x_room')->where('room_id',$value['room_id'])->find();  
            }
            $this->assign('title',"购买记录");
    }
    for($i=0;$i<count($room);$i++)
     {
      if($room[$i]['beg_time']==0)
      {
      $room[$i]['zhuangtai']=begintime($room[$i]['create_time']);
      }
      else if($room[$i]['beg_time']!=0&&$room[$i]['longtime']==0)
      {
      $room[$i]['zhuangtai']="<a style='text-decoration:none;color:green;'>正在直播|||</a>";  
      }
      else
      {
      $room[$i]['zhuangtai']="时长:".$room[$i]['longtime']."分钟"; 
      }
     }
    $this->assign('user_id',$user_id);
    $this->assign('room',$room);
    return $this->fetch();
}

//微课中心里关注列表
public function weike_follow()
{
    session_start();
    $user_id=$_SESSION['user_id'];
    $teacher=array();
    $data=Db::table('x_attn_recoder')->where('user_id',$user_id)->select();
    foreach ($data as $key => $value) {
    if(Db::table('x_user')->where('user_id',$value['teacher_id'])->find())  
    $teacher[]=Db::table('x_user')->where('user_id',$value['teacher_id'])->find();  
    }
    $this->assign('teacher',$teacher);
    $this->assign('user_id',$user_id);
    return $this->fetch();
}

//修改订阅的栏位
public function edit_dingyue()
{
    session_start();
    $dingyue=Request::instance()->post('dingyue');
    $dingyue=json_decode($dingyue);
    $_SESSION['dingyu']=$dingyue;

}
//邀请卡页面
public function person_invite()
{
    $user_id=Request::instance()->get('user_id');
    $room_id=Request::instance()->get('room_id');
    $person=Db::table('x_weixin_user')->where('id',$user_id)->find();
    $this->assign('room_id',$room_id);
    $this->assign('person',$person);
    return $this->fetch();
}
//通用页面
public function tongyong()
{
  $type=Request::instance()->get('type');
  switch ($type) {
    case '1':
      $content=file_get_contents('use_method.txt');
      break;
    case '2':
      $content=file_get_contents('lianxi.txt');
      break;
    case '3':
      $content=file_get_contents('yingshi.txt');
      break;
    default:
      # code...
      break;
  }
  $this->assign('content',$content);
  return $this->fetch();
}
//删除个人直播间的轮播图
public function del_person_lunbo()
{
  $id=Request::instance()->post('id');
  Db::table('x_person_lunbo')->where('id',$id)->delete();
}

//聊天室ppt 轮播图的添加
//轮播图添加
public function weike_img_lunbo()
{
    session_start();
    $room_id=Request::instance()->get('room_id');
    if(Request::instance()->isAjax())
    {

         //如果存在轮播图先把以前的删除了
        Db::table('x_room_lunbo')->where('room_id',$room_id)->delete();
        $data=json_decode(htmlspecialchars_decode(Request::instance()->post('data')),true);
        $senddata=array();
        foreach ($data as $key => $val){
          if($val[0]=="")
            break;
          DB::table('x_room_lunbo')->insert(array('room_id'=>$room_id,'img_cover'=>$val[0]));
        }
        return json(["code"=>1]);
    }
    else{
    //如果存在轮播图先渲染出来
    $count=Db::table('x_room_lunbo')->where('room_id',$room_id)->count();
    $lunbo=Db::table('x_room_lunbo')->where('room_id',$room_id)->order('id desc')->select(); 
    for($i=$count;$i<20;$i++)
    {
        $lunbo[$i]['img_cover']="";
        $lunbo[$i]['src']="";
        $lunbo[$i]['id']="";
    }
    $this->assign('RoomId',$room_id);
    $this->assign('count',$count);
    $this->assign('lunbo',$lunbo);
    return $this->fetch();
    }
}

//开始和结束课程的按钮
public function beg_end()
{
//room_id type=1 开始课程 type=2 结束课程  
$room_id=Request::instance()->get('room_id');
$type   =Request::instance()->get('type');
if($type==1)
{
  Db::table('x_room')->where('room_id',$room_id)->setField('beg_time',time());
}
else
{
  //算出课程的时长
  $room=Db::table('x_room')->where('room_id',$room_id)->find();
  $minute=number_format((time()-$room['beg_time'])/60,0);
  Db::table('x_room')->where('room_id',$room_id)->setField('longtime',$minute);
}
}
//提现记录
public function weike_tixianjilu()
{
  session_start();
  $user_id=$_SESSION['user_id'];
  $list=Db::table('x_getmoney_list')->where('user_id',$user_id)->order('id desc')->select();
  $this->assign('list',$list);
  return $this->fetch();
}
//累计收益情况
public function weike_leijishouyi()
{
   session_start();
   $user_id=$_SESSION['user_id'];
   //得到下面所有课程
   $list=array();
   $room=Db::table('x_room')->where('user_id',$user_id)->select();
   foreach ($room as $key => $value) {
     //得到课程下面所有记录
     $list_buy=Db::table('x_pay_recoder')->where('room_id',$value['room_id'])->select();
     foreach ($list_buy as $key1 => $val) {
        $list[]=$val;
     }
   }

   //得到购买人姓名 时间 文章标题 
   for($i=0;$i<count($list);$i++)
   {
    //得到房间标题
    $title=Db::table('x_room')->where('room_id',$list[$i]['room_id'])->find();
    $list[$i]['title']=$title['title'];
    //得到购买人姓名
    $person=Db::table('x_user')->where('user_id',$list[$i]['user_id'])->find();
    $list[$i]['nickname']=$person['nickname'];
   }
   $this->assign('list',$list);
   return $this->fetch();
}

public  function shijia_huodong()
{
	 //判断是不是其他人进入微课中心
    session_start();
    if(isset($_SESSION['user_id']))
    {
       //得到用户信息
	   $data=Db::table('x_weixin_user')->where('id',$_SESSION['user_id'])->find();
	   $url='http://m.fulejiaweike.com/checkVoter?openId='.$data['openid'].'&name='.$data['nickname'];
	   $this->redirect($url);
    }   
    $_SESSION['url']=Request::instance()->url(true);
    $this->byauth(); 
}
//获取用户基本信息
public function get_weixinUserByOpenid($openId)
{
        //判断access_token缓存是否过期
        if(jugement_token_value())
        {
        $access_token=get_access_token_ache();
        }
        else{
        $access_token=$this->getAccess_token();
        }    
        $url  ="https://api.weixin.qq.com/cgi-bin/user/info?access_token={$access_token}&openid={$openId}&lang=zh_CN";
        $result=$this->http_url($url);
        return json_decode($result);  //json字符串转换成json数组
}
//获取access_token
public function getAccess_token()
{
        $appid="wxcd4dce13c9fb1a0a";   //微信公众号唯一标识
        $secret="a9f3c9753b70b42573fdd6440090c1c6";  //秘钥
        $url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$secret}";
        $json=$this->http_url($url);
        $result=json_decode($json);
        //写入自己定义的缓存文件
        $data=array();
        $data['access_token']=$result->access_token;
        $data['time_out']=time();
        $string=json_encode($data);
        file_put_contents('token.txt',$string);
        return $result->access_token;
}
//启用curl 模仿游览器使用https协议访问链接
private function http_url($url,$data=null)
{
        //1.初始化，创建一个新cURL资源
        $ch = curl_init();
        //2.设置URL和相应的选项
        curl_setopt($ch, CURLOPT_URL, $url);
        //curl_setopt($ch, CURLOPT_HEADER, 0);
        if(!empty($data)){
            curl_setopt($ch,CURLOPT_POST,1);
            curl_setopt($ch,CURLOPT_POSTFIELDS,$data);
        }
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);//不检测服务器的证书是否由正规浏览器认证过的授权CA颁发
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);//不检测服务器的域名与证书上的是否一致
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);//禁止curl资源直接输出
        //3.抓取URL并把它传递给浏览器
        $opt=curl_exec($ch);
        //4.关闭cURL资源，并且释放系统资源
        curl_close($ch);
        return $opt;
}
//如果user_id不存在的话根据openid获取用户信息存入数据库返回user_id
public function is_user_id_null($openid)
{
     $result=$this->get_weixinUserByOpenid($openid);
    //获取微信用户的信息存入数据库中
        $data=array(
            'subscribe'=>$result->subscribe,
            'openid'  =>$result->openid,
            'nickname'=>$result->nickname,
            'sex'     =>$result->sex,
            'language'=>$result->language,
            'city'    =>$result->city,
            'province'=>$result->province,
            'headimgurl'=>$result->headimgurl,
            'subscrbe_time'=>date('Y-m-d'),
        );
      return  Db::table('x_weixin_user')->insertGetId($data);
}
//报错页面
public function _empty(){
    $this->error('页面不存在即将返回');
}

}